package com.lsj.service.impl;

import cn.hutool.core.convert.Convert;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lsj.config.redis.RedisKey;
import com.lsj.core.lock.DistributedLock;
import com.lsj.core.lock.LockKey;
import com.lsj.core.util.QueryHelperUtil;
import com.lsj.dto.sys.RoleMenuDto;
import com.lsj.mapper.SysRoleMenuMapper;
import com.lsj.mapper.entity.SysRoleMenu;
import com.lsj.service.MenuService;
import com.lsj.service.RoleMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author:lin.sj
 * @Data:2021/7/8 21:44
 * @Desc:
 */
@Service
@CacheConfig(cacheNames = RedisKey.USER_KEY)
public class RoleMenuServiceImpl implements RoleMenuService {
    @Autowired
    SysRoleMenuMapper sysRoleMenuMapper;
    @Autowired
    MenuService menuService;

    /**
     * @Author: lin.sj
     * @Date: 2021/7/13 22:29
     * @Desc:
     * 1.绑定前台传入的角色与菜单关系信息
     * 2.为角色更新权限，更新完毕后，需要从redis中去除用户加载的信息(因为权限变了),通过CacheEvict操作
     **/
    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(allEntries = true)
    @DistributedLock(LockKey.menu_tree_key)
    public void updateMenuForRole(RoleMenuDto dto) {
        //删除当前角色关联的菜单
        LambdaQueryWrapper<SysRoleMenu> w = QueryHelperUtil.getLambdaWrapper(SysRoleMenu.class);
        w.eq(SysRoleMenu::getRoleId,dto.getRoleId());
        sysRoleMenuMapper.delete(w);
        //重新插入所有角色与菜单关联信息
        for(Long menuId:dto.getMenuIds()){
            SysRoleMenu roleMenu = new SysRoleMenu().setRoleId(dto.getRoleId()).setMenuId(menuId);
            sysRoleMenuMapper.insert(roleMenu);
        }
    }
    /**
     * @Author: lin.sj
     * @Date: 2021/8/18 20:23
     * @Desc: 根据角色获取关联的菜单Id
     **/
    @Override
    public List<String> getMenuIdsByRoleId(Long roleId) {
        LambdaQueryWrapper<SysRoleMenu> w = QueryHelperUtil.getLambdaWrapper(SysRoleMenu.class);
        w.eq(SysRoleMenu::getRoleId,roleId);
        List<SysRoleMenu> sysRoleMenus = sysRoleMenuMapper.selectList(w);
        List<String> menuIds = sysRoleMenus.stream().map(rm -> Convert.toStr(rm.getMenuId())).collect(Collectors.toList());
        return menuIds;
    }


}

